package pattern.observer.userdefined.subject

import pattern.observer.userdefined.observer.{CurrentConditionDisplay, Observer}

import scala.collection.mutable.ArrayBuffer

/**
 * Created by root on 15-9-17.
 */
class WeatherData extends Subject{
  private val observers = new ArrayBuffer[Observer]()
  private var temperature:Float = _
  private var humidity:Float = _
  private var pressure:Float = _

  def measurementsChanged(): Unit ={
    notifyObservers()
  }

  def setMeasurements(temperature:Float,humidity:Float,pressure:Float): Unit ={
    this.temperature = temperature
    this.humidity = humidity
    this.pressure = pressure
    measurementsChanged()
  }
  override def registerObserver(o: Observer): Unit = {
    observers += o
  }

  override def removeObserver(o: Observer): Unit = {
    val i = observers.indexOf(o)
    if(i>0) observers.remove(i)
  }

  override def notifyObservers(): Unit = {
    for(observer <- observers) observer.update(temperature,humidity,pressure)
  }
}
object WeatherData{
  def main (args: Array[String]): Unit = {
    val weatherData = new WeatherData
    val display1=new CurrentConditionDisplay(weatherData)
    val display2=new CurrentConditionDisplay(weatherData)
    weatherData.setMeasurements(1.0f,1.0f,1.0f)
  }
}